﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils;
namespace zmMoniter
{

    public partial class treeListEq : zmMoniter.Basefrm
    {
        struct CmbInfo
        {
            public int _key; public string _text;
            public CmbInfo(int key, string text)
            {
                _key = key; _text = text;
            }
            public override string ToString()
            {
                return _text;
            }
        }
        private mainForm main = null;
        public int iDeckID;
        public treeListEq(mainForm frm)
        {
            InitializeComponent();
            this.main = frm;
            this.iDeckID = -1;
            if (main.sPrv != "1")
            {
                gridCol_MbUse.Visible = false;
                //panelControl2.Visible = false;
            }
        }
        private void selectDam(string damName)
        {
            cmbox_damBlock.Properties.Items.Clear();
            cmbox_damBlock.Text = (string)cmbox_damBlock.Tag;
            grid_layer.DataSource = null;
            if (damName == "上坝块")
            {
                for (int i = 1; i < 20; i++)
                {
                    cmbox_damBlock.Properties.Items.Add(new CmbInfo(i, "坝段" + i.ToString()));
                }
            }
            else if (damName == "下坝块")
            {
                for (int i = 2; i < 19; i++)
                {
                    cmbox_damBlock.Properties.Items.Add(new CmbInfo(i, "坝段" + i.ToString()));
                }
            }
        }
        private void cmbox_dam_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectDam(cmbox_dam.EditValue.ToString());
        }
        private void selectDamBlock(string sDam, string sDamBlock)
        {
            cmbox_deck.Properties.Items.Clear();
            cmbox_deck.Text = (string)cmbox_deck.Tag;
            grid_layer.DataSource = null;
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();
            string sSQL = "";
            if (sDam == "上坝块")
                sSQL = "SELECT * FROM 仓面信息 WHERE 上下游块='S' AND 坝段=" + sDamBlock;
            else if (sDam == "下坝块")
                sSQL = "SELECT * FROM 仓面信息 WHERE 上下游块='X' AND 坝段=" + sDamBlock;
            DataTable dt = db.ReturnDataTable(sSQL);
            db.CloseConn();
            if (dt == null)//modify by lance 2013-1-20
                return;
            int iCount = dt.Rows.Count;
            for (int i = 0; i < iCount; i++)
            {
                DataRow dataRow = dt.Rows[i];
                int iIDSQL = int.Parse(dataRow["编号"].ToString().Trim());
                string sNameSQL = dataRow["仓面名称"].ToString().Trim();
                //string sMinHeight = dataRow["最低高程"].ToString().Trim();
                //string sMaxHeight = dataRow["最高高程"].ToString().Trim();
                // string sVibRange = dataRow["振捣边界点"].ToString().Trim();
                // string sDeckRange = dataRow["仓面控制点"].ToString().Trim();
                cmbox_deck.Properties.Items.Add(new CmbInfo(iIDSQL, sNameSQL.ToString()));

            }
        }
        private void cmbox_damBlock_SelectedIndexChanged(object sender, EventArgs e)
        {
            CmbInfo p = new CmbInfo();
            p = (CmbInfo)(cmbox_damBlock.SelectedItem);
            int value = p._key;
            string damName = cmbox_dam.EditValue.ToString();
            selectDamBlock(damName, value.ToString());
        }
        private void selectDeck(int iDeckID)
        {

            loadLayerDate(iDeckID);
            loadDeviceDate();
            setDeckState(iDeckID);
            // this.main.showDeck2d(iDeckID.ToString());//暂时不显示仓面图形

        }
        private void cmbox_deck_SelectedIndexChanged(object sender, EventArgs e)
        {
            CmbInfo p = new CmbInfo();
            p = (CmbInfo)(cmbox_deck.SelectedItem);
            int value = p._key;
            iDeckID = value;
            selectDeck(value);
        }
        private void loadLayerDate(int value)
        {
            grid_layer.DataSource = null;
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();

            string sSQL = "SELECT 铺层信息表.编号,铺层信息表.层编号,铺层信息表.层面积,铺层信息表.振捣面积,铺层信息表.剩余未振捣面积," +
                "(case when 仓面信息.开仓状态=1 then '施工中' when 仓面信息.开仓状态=0 then '关闭' when 仓面信息.开仓状态=2 then '待施工' else '完成' end) 施工状态 " +
                "FROM 铺层信息表 LEFT OUTER JOIN 仓面信息 ON 铺层信息表.仓面号 = 仓面信息.编号 " +
                " WHERE 仓面号=" + value + " Order by 层编号 DESC";
            DataTable dt = db.ReturnDataTable(sSQL);
            db.CloseConn();
            if (dt == null)//modify by lance 2013-1-20
                return;
            int iCount = dt.Rows.Count;
            if (iCount == 0)
                return;


            /*for (int i = 0; i < iCount; i++)
            {
                DataRow dataRow = dt.Rows[i];

                float fArea = float.Parse(dataRow["剩余未振捣面积"].ToString().Trim());
                if (fArea > 0)
                    dataRow["施工状态"] = "施工中";
                else
                    dataRow["施工状态"] = "完  成";
            }
            */
            grid_layer.DataSource = dt;

        }
        private DataTable UpdateDeviceDataTable(DataTable argDataTable)
        {
            DataTable dt = new DataTable();
            //克隆表结构
            dt = argDataTable.Clone();
            foreach (DataColumn column in dt.Columns)
            {
                if (column.ColumnName == "是否启用")
                {
                    //修改列类型
                    column.DataType = typeof(Boolean);
                }
            }
            foreach (DataRow oldrow in argDataTable.Rows)
            {
                DataRow row = dt.NewRow();
                row["编号"] = oldrow["编号"];
                //row["仓面号"] = oldrow["仓面号"];
                //row["仓面名称"] = oldrow["仓面名称"];
                row["型号"] = oldrow["型号"];
                row["使用状态"] = oldrow["使用状态"];
                row["是否启用"] = Convert.ToBoolean(oldrow["是否启用"]);//你改过DataType的行
                row["标识"] = Convert.ToInt16(oldrow["标识"]);//你改过DataType的行                
                dt.Rows.Add(row);
            }
            return dt;
        }
        private void loadDeviceDate()
        {
            grid_device.DataSource = null;
            //string sSQL = "select 振捣设备基本信息表.编号,振捣设备基本信息表.型号,振捣设备基本信息表.使用设备状态," +
            //   "(case when 振捣设备使用记录表.仓面号=" + value + " then 1 else 0 end) as 是否启用,0 as 标识" +
            //   " FROM 振捣设备基本信息表 LEFT OUTER JOIN " +
            //   "振捣设备使用记录表 ON 振捣设备基本信息表.编号 = 振捣设备使用记录表.设备编号"+
            //" WHERE 振捣设备使用记录表.结束时间 IS NULL";

            //            string sSQL = @"SELECT   振捣设备基本信息表.编号, 振捣设备基本信息表.型号, 在线设备.仓面号, 0 as 标识,在线设备.仓面名称,
            //                振捣设备使用状态表.名称 AS 使用状态, (case when 在线设备.仓面号=" +value+@"  and 振捣设备使用状态表.名称='在线' then 1 else 0 end) 是否启用, 在线设备.开始时间
            //                FROM      振捣设备基本信息表  LEFT OUTER JOIN
            //                振捣设备使用状态表 ON 振捣设备基本信息表.使用设备状态 = 振捣设备使用状态表.编号 LEFT OUTER JOIN
            //                在线设备 ON 振捣设备基本信息表.编号 = 在线设备.设备编号 WHERE 在线设备.结束时间 IS NULL";
            string sSQL = @"SELECT 编号, 型号, 使用状态,(case when 仓面号=" + iDeckID + " then 1 else 0 end) as 是否启用,0 as 标识 FROM 振捣设备";
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();
            DataTable dt = db.ReturnDataTable(sSQL);
            if (dt == null || dt.Rows.Count == 0)//modify by lance 2013-1-20
                return;
          
            db.CloseConn();
            grid_device.DataSource = UpdateDeviceDataTable(dt);

        }
        private void setDeckState(int deckID)
        {
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();
            string sSQL = "SELECT 编号,开仓状态 FROM 仓面信息 WHERE 编号=" + deckID;
            DataTable dt = db.ReturnDataTable(sSQL);
            db.CloseConn();
            if (dt == null)//modify by lance 2013-1-20
                return;
            int iCount = dt.Rows.Count;
            if (iCount == 0)
                return;
            DataRow dataRow = dt.Rows[0];
            int iState = int.Parse(dataRow["开仓状态"].ToString());
            main.setDeckState(deckID, iState);
            
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            /* 
             int inRow = e.FocusedRowHandle;
             if (inRow < 0)
                 return;
             if(inRow>=gridView1.RowCount)
                 return;
             //取得选定行信息  
             string sID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "编号").ToString();
             CmbInfo p = new CmbInfo();
             p = (CmbInfo)(cmbox_deck.SelectedItem);
             string value = p._key.ToString();
             this.main.showLayer2d(value, sID);
             */
        }
        public void upDateDeck(int iNewDeckID)
        {
            if (iNewDeckID != iDeckID)
                return;
            selectDeck(iDeckID);
        }
        public void saveDevice()
        {
            DateTime now = System.DateTime.Now;
            DataTable dtSource1 = (DataTable)grid_device.DataSource;
            //DataTable dtSource = dtSource1.Copy();
            //DataView dtView = dtSource.DefaultView;
            //dtView.RowFilter = "标识=1";
            //DataTable dt = dtView.ToTable();
            //if (dt.Rows.Count == 0)
            //    return;
            ArrayList al = new ArrayList();
            string sDeviceID = "";
            for (int i = 0; i < dtSource1.Rows.Count; i++)
            {
                //row["使用设备状态"] 
                //string sSQL = "";
                if (dtSource1.Rows[i]["标识"].ToString() != "1")
                    continue;
                string sID = dtSource1.Rows[i]["编号"].ToString();//设备编号
                string isOnLine = dtSource1.Rows[i]["使用状态"].ToString();//是否在线
                bool bUse = (bool)dtSource1.Rows[i]["是否启用"];//启用/关闭

                if (bUse)//启用
                {
                    if (isOnLine == "在线")
                    {
                        DialogResult DlgResult = MessageBox.Show(sID + "号设备正在使用,是否继续调度?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                        if (DlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            Devices.startDevice(sID, iDeckID);
                        }
                    }
                    else
                    {
                        Devices.startDevice(sID, iDeckID);
                    }
                }
                else//关闭
                {
                    if (isOnLine == "在线")
                    {
                        DialogResult DlgResult = MessageBox.Show(sID + "号设备正在使用,是否停用?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                        if (DlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            Devices.stopDevice(sID);
                        }
                    }
                    else
                    {
                        Devices.stopDevice(sID);
                    }
                }

                if (sDeviceID != "")
                    sDeviceID += ";" + sID;
                else
                    sDeviceID += sID;
            }
            /*
            foreach (DataRow row in dt.Rows)
            {
                //row["使用设备状态"] 
                string sSQL = "";
                string sID = row["编号"].ToString();//设备编号
                string isOnLine = row["使用状态"].ToString();//是否在线
                bool bUse = (bool)row["是否启用"];//启用/关闭

                if (bUse)//启用
                {
                    if (isOnLine == "在线")
                    {
                        DialogResult DlgResult = MessageBox.Show(sID + "号设备正在使用,是否继续调度?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                        if (DlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            Devices.startDevice(sID, iDeckID);
                        }
                    }
                    else
                    {
                        Devices.startDevice(sID, iDeckID);
                    }                  
                }
                else//关闭
                {
                    if (isOnLine == "在线")
                    {
                        DialogResult DlgResult = MessageBox.Show(sID + "号设备正在使用,是否停用?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                        if (DlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            Devices.stopDevice(sID);
                        }
                    }
                    else
                    {
                        Devices.stopDevice(sID);                   
                    }
                }              
               
                if (sDeviceID != "")
                    sDeviceID += ";" + sID;
                else
                    sDeviceID += sID;             
            }
             * */
            loadDeviceDate();
            if (sDeviceID != "")
                main.seedMessage("02;" + sDeviceID);
        }
        public void reSetDevice()
        {
            loadDeviceDate();
            setDeckState(iDeckID);
        }
        private void tbtn_save_Click(object sender, EventArgs e)
        {
            saveDevice();
        }
        private bool existDeviceRecord(string sID)
        {
            bool bResult = false;
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();
            string sSQL = "SELECT * FROM 振捣设备基本信息表 WHERE (使用设备状态 = 0) AND (是否分配 = 0) AND (编号 = " + sID + ")";
            if (db.GetRecordCount(sSQL) > 0)
                bResult = true;
            return bResult;
        }
        private void sbtn_reSet_Click(object sender, EventArgs e)
        {
            reSetDevice();
        }

        private void grid_device_Click(object sender, EventArgs e)
        {

        }

        private void gridView2_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            /*
            int intRowHandle = e.RowHandle;
            bool bUse = Convert.ToBoolean(gridView1.GetRowCellValue(intRowHandle, "gridCol_MbUse"));  
            bool bSUse = Convert.ToBoolean(gridView1.GetRowCellValue(intRowHandle, "gridCol_SMvUse"));
            if (bUse != bSUse)
            {
                gridView2.Appearance.FocusedRow.BackColor = Color.Red;

            }
            else
            {
                gridView2.Appearance.FocusedRow.BackColor = Color.White;
            }*/

        }

        private void gridView2_Click(object sender, EventArgs e)
        {

        }

        private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit ckEdit = (CheckEdit)sender;
            int inRow = gridView2.FocusedRowHandle;
            int i = int.Parse(gridView2.GetRowCellValue(inRow, "标识").ToString());
            gridView2.SetRowCellValue(inRow, "是否启用", ckEdit.Checked);
            if (i == 1)
            {
                gridView2.SetRowCellValue(inRow, "标识", 0);
            }
            else
            {
                gridView2.SetRowCellValue(inRow, "标识", 1);
            }
            if (main.sPrv == "1")
            {
                main.barBtn_SaveDevice.Enabled = true;
            }
            main.barBtn_reSetDevice.Enabled = true;
        }

        private string setDam(string sDam)
        {
            string sDamName = "";
            if (sDam == "X")
            {
                sDamName = "下坝块";
            }
            else
            {
                sDamName = "上坝块";
            }
            cmbox_dam.Text = sDamName;
            selectDam(sDamName);
            return sDamName;
        }
        private bool setDamBlock(string sDam, string sDamBlock)
        {
            bool bResult = false;
            cmbox_damBlock.EditValue = "坝段" + sDamBlock;
            selectDamBlock(sDam, sDamBlock);
            return bResult;
        }
        private bool setDeck(string sDeckName, string sDeckID)
        {
            bool bResult = false;
            //cmbox_deck.EditValue = sDeckName;
            for (int i = 0; i < cmbox_deck.Properties.Items.Count; i++)
            {
                CmbInfo p = (CmbInfo)(cmbox_deck.Properties.Items[i]);
                if (p._key == int.Parse(sDeckID))
                    cmbox_deck.SelectedItem = p;
            }
            selectDeck(int.Parse(sDeckID));
            return bResult;
        }
        public void setDateByBlock(string sBockName)
        {
            string[] sItem = sBockName.Split('-');
            if (sItem.Length != 2)
                return;
            PublicDataCls db = new PublicDataCls();
            db.OpenConn();
            string sSQL = "SELECT 编号,仓面名称 FROM 仓面信息 WHERE 坝段=" + sItem[0] + " AND 上下游块='" +
                sItem[1] + "' Order by 最高高程 DESC";
            DataTable dt = db.ReturnDataTable(sSQL);
            db.CloseConn();
            if (dt == null)//modify by lance 2013-1-20
                return;
            int iCount = dt.Rows.Count;
            if (iCount == 0)
                return;
            DataRow dataRow = dt.Rows[0];

            string sDeckID = dataRow["编号"].ToString().Trim();
            string sDeckName = dataRow["仓面名称"].ToString().Trim();
            setDateByDeck(sBockName, sDeckID);
        }
        public void setDateByDeck(string sDeckName, string sDeckID)
        {
            string[] sItem = sDeckName.Split('-');
            if (sItem.Length <2)
                return;
            //setDam(sItem[1]);
            setDamBlock(setDam(sItem[1]), sItem[0]);
            setDeck(sDeckName, sDeckID);
        }
        public void setDateByLayer(string sDeckName, string sDeckID, string sLayerID)
        {
            string[] sItem = sDeckName.Split('-');
            if (sItem.Length != 3)
                return;

            //setDam(sItem[1]);
            setDamBlock(setDam(sItem[1]), sItem[0]);
            setDeck(sDeckName, sDeckID);
            int iRowID = int.Parse(sLayerID);

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                int nowId = int.Parse(gridView1.GetRowCellValue(i, "编号").ToString());
                if (nowId == iRowID)
                {
                    gridView1.FocusedRowHandle = i;
                }
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

            int inRow = e.RowHandle;
            if (inRow < 0)
                return;
            if (inRow >= gridView1.RowCount)
                return;
            //取得选定行信息  
            string sID = gridView1.GetRowCellValue(inRow, "编号").ToString();
            CmbInfo p = new CmbInfo();
            p = (CmbInfo)(cmbox_deck.SelectedItem);
            string value = p._key.ToString();
            this.main.showLayer2d(value, sID);
        }
    }
}